// attachmentManager.js
var attsize  ='';
function attachmentHtmlStr(attData) {
	var filesize = parseInt(attData.size);
	if (attData.size == '') {
		filesize = '';
	}
	 attsize = bytesToSize(filesize);
	var downloadStatus = '';

	if (attData.isdownload == 1) {//已下载
	   
		downloadStatus = "base_none_item";
	}
//	return '<div class="weui_cell attachment_cell" progress_id="' + attData.id + '" >' + '<div class="weui_cell_bd weui_cell_primary">' + '<div class="materials_title ">' + attData.name + '</div>' + '<div class="materials_content">' + '<div class="materials_download">' + '<div class="materials_size">' + '<span>' + attsize + '</span>' + '</div>' 
//	+ '<div id="prodiv' + attData.id + '" class="materials_progress' + downloadStatus + '">' 
//	+ '<div class="container">' + '<div class="weui_progress">' + '<div class="weui_progress_bar">' +
//	 '<div class="weui_progress_inner_bar" id="' + attData.id + '" style="width: 0;">' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>';
  return '  <div class="font16 attachment_cell" progress_id="' + attData.id + '" > <a class="a_style_xiazai"  >' 
  + attData.name + '<span style="margin-left: 10px;margin-right: 10px;color: #666666;">('+ attsize+
  ')</span><img  id="' + attData.id + '" class="img_style_xiazai ' + downloadStatus + '" src="../../image/icon_xiazai.png" /></a></div>';
   }

function setupAttachmentCellClick() {
	$('.attachment_cell').unbind('click');
	$('.attachment_cell').click(function(event) {
		var attid = $(this).attr('progress_id');
		var sql = 'SELECT * FROM t_attachment WHERE id = ' + attid + ';';
		selectSQL(sql, function(ret, err) {
	
			if (ret.status && ret.data != null && ret.data != '' && ret.data != undefined) {
				var attData = ret.data[0];
				var fileurl = attData.url;
				var filename = attData.name;
				var filepath = api.cacheDir + attData.localpath;
				var att_id = attData.id;
				var isdownload = attData.isdownload;
	
				if (isdownload == 1) {//已下载
					openLocalFile(filepath);
				} else {//未下载则下载
				//判断网络类型
				var connectionType = api.connectionType+'';  
		
				if(connectionType !='wifi'){
				
					api.confirm({
						title : '非wifi网络情况',
						msg : '消耗你' + attsize,
						buttons : ['确定', '取消']
					}, function(ret, err) {
						var index = ret.buttonIndex;
				
						if (index == 1) {
                            
							api.sendEvent({
								name : 'startDownloadAttachmentNotifi',
								extra : {
									id : att_id,
									url : fileurl,
									name : filename
								}
							});
						} else {
						}
					});
					}else{
					
					api.sendEvent({
								name : 'startDownloadAttachmentNotifi',
								extra : {
									id : att_id,
									url : fileurl,
									name : filename
								}
							});
					}
				}

			} else {
//				api.toast({
//					msg : '数据异常'
//				});
			}
		});

	});


}

//根据后缀是否为图片打开本地文件预览
function openLocalFile(filepath) {
	var arr = new Array('jpg', 'png', 'jpeg');
	var gifArr = new Array('gif', 'bmp');
	var ext = filepath.replace(/.+\./, "");
	var videoArr = new Array('mp4', 'flv', 'rm', 'rmvb', 'wmv', 'avi', '3gp', 'mkv');
	if (gifArr.toString().indexOf(ext) > -1){
		openGif(filepath);
	}else if(arr.toString().indexOf(ext) > -1) {
		openImage(filepath);
	} else if (videoArr.toString().indexOf(ext) > -1) {//视频
		// api.openWin({useWKWebView:true,
 	// 	    name: 'BaiDuWebVideo',
 	// 	    url: '../Study/',
 	// 	    pageParam: {
 	// 	    	title: '',
 	// 	        url: filepath,
 	// 	        token: ''
 	// 	    },
 	// 	    slidBackEnabled: false
 	// 	});
		// return;
		// api.openVideo({
		// 	url : filepath
		// });
		var videoPlayer = api.require('videoPlayer');
		videoPlayer.play({
		    path : filepath,
		    texts: {
		        head: {
		            title: ''
		        }
		    },
		    styles : {
		    	head : {
		    		backSize : 24,
		    		backImg : 'widget://image/vp_back.png',
		    		setSize : 24,
		    		setImg : 'widget://image/vp_more.png'
		    	},
		    	foot :{
		    		playSize : 24,
		    		playImg : 'widget://image/vp_play.png',
		    		pauseImg : 'widget://image/vp_pause.png',
		    		nextSize : 24,
		    		nextImg : 'widget://image/vp_next.png'
		    	}
		    }
		}, function(ret, err) {
		});
	} else {
		openDocReader(filepath);
	}
}

//打开本地器应用文件浏览
function openDocReader(filepath) {
	var docReader = api.require('docReader');
	docReader.open({
		path : filepath
	});
}
function openGif(filepath, extendData){
	var gifParam = {
        filepath : filepath
    };
	if (extendData != null) {
		gifParam['extendData'] = extendData;
	}  
	api.openWin({useWKWebView:true,
	    name : 'ShowImageFrame',
		url : '../Study/ShowImageFrame.html',
		bgColor : '#F0F0F0',
	    pageParam: gifParam,
	    vScrollBarEnabled : true,
		hScrollBarEnabled : false,
		slidBackEnabled : false
	});
}
//打开本地相册
function openImage(filepath, extendData) {
	var imgParam = {
        imageurl : filepath
    };
	if (extendData != null) {
		imgParam['extendData'] = extendData;
	} 
	api.openWin({useWKWebView:true,
	    name: 'PicturePreviewPage',
	    url: '../Study/PicturePreviewPage.html',
	    pageParam: imgParam,
		slidBackEnabled : false
	});
	// var photoBrowser = api.require('photoBrowser');
	// photoBrowser.open({
	// 	images : [filepath],
	// 	bgColor: '#000'
	// }, function(ret, err){
	// 	if (ret.eventType == 'click') {//点击了图片
	// 		photoBrowser.close();
	// 	}
	// });
	// var imgages = [filepath];
	// var imageBrowser = api.require('imageBrowser');
	// imageBrowser.openImages({
	// 	imageUrls : imgages,
	// 	showList : false,
	// 	activeIndex : 0,
	// }, function(ret, err) {
	// });
}

//附件下载进度通知
function setupDownloadAttNotifi() {
	api.addEventListener({
		name : 'downloadAttachmentNotifi'
	}, function(ret, err) {
		var result = ret.value.ret;
		var attid = ret.value.attid;
		var prodivID = '#'+ attid;
//		var progressID = '#' + attid;
//		var width = "width:" + result.percent + "%;";
//		$(progressID).attr('style', width);

		if (result.state == 1) {
			$(prodivID).addClass('base_none_item');
		}
	});
}

//保存数据至db
function saveAttDatasToDb(attDatas, id) {


	var j = 0;
	var count = attDatas.length;
	for (var i = 0; i < count; i++) {
		var attData = attDatas[i];
		// if (id == '#stu_attachmentTableView') {//如果是作业章节

		// 	insertData('t_attachment', attData, function(ret, err) {
		// 		j++;
		// 		if (j == count) {
		// 			if (ret) {//第一次提交,即为插入操作
		// 				selectBDAttDatas(attDatas, id);
		// 			} else {//重复提交，更新操作
		// 				var sql = "UPDATE t_attachment SET  isdownload = '0', name = '" + attData.name + "',url = '" + attData.url + "',size = '" + attData.size + "' WHERE id = " + attData.id + ";";
		// 				executeSQL(sql, function(ret, err) {
		// 					selectBDAttDatas(attDatas, id);

		// 				});
		// 			}
		// 		}

		// 	});
		// } else {
			insertData('t_attachment', attData, function(ret, err) {
			
				j++;
				if (j == count) {

					selectBDAttDatas(attDatas, id);

				}

			});
		// }
	}

}

function selectBDAttDatas(attDatas, id) {
	for (var i = 0; i < attDatas.length; i++) {
		var attData = attDatas[i];
		var sql = 'SELECT * FROM t_attachment WHERE id = ' + attData.id + ';';
		selectSQL(sql, function(ret, err) {
			if (ret.status && ret.data != null && ret.data != '' && ret.data != undefined) {
				var att_data = ret.data[0];
               
				if (id == '#teacher_attachmentTableView') {
					$('#teacher_attachmentTableView').append(attachmentHtmlStr(att_data));
			
				} else if (id == '#stu_attachmentTableView') {
					$('#stu_attachmentTableView').append(attachmentHtmlStr(att_data));
				} else if (id == '') {
					$('#attachmentTableView').append(attachmentHtmlStr(att_data));
				}else if(id=='#rz_attachmentTableView'+att_data.id){
				  $('#rz_attachmentTableView'+ att_data.id).append(attachmentHtmlStr(att_data));
				}

				setupAttachmentCellClick();
			} else {
//				api.toast({
//					msg : '数据异常'
//				});
			}
		});
	}
}

//字节转换
function bytesToSize(bytes) {
	if (bytes == '') return "未知大小";
	if (bytes === 0)
		return '0 B';

	var k = 1024;

	sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

	i = Math.floor(Math.log(bytes) / Math.log(k));

	return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
	//toPrecision(3) 后面保留一位小数，如1.0GB                                                                                                                  //return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}  